package com.own.system.config.security.Service;

import com.own.system.entity.Permission;
import com.own.system.entity.User;
import com.own.system.service.PermissionService;
import com.own.system.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户认证处理器类
 */

@Component
public class CustomerUserDetailsService implements UserDetailsService {
    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        User user = userService.findUserByUserName(username);
        //判断对象是否为空
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        //查询当前登录用户拥有的权限列表
        List<Permission> permissionList = permissionService.findPermissionListByUserId(user.getId());
        //获取对应的权限编码
        List<String> codeList = permissionList.stream()//获取权限编码
                .filter(Objects::nonNull)//过滤空值
                .map(Permission::getCode)//获取权限编码
                .filter(Objects::nonNull)//过滤空值
                .collect(Collectors.toList());//封装权限编码
        //将权限编码封装到权限集合中，转换为数组
        String[] authorities = codeList.toArray(new String[codeList.size()]);
        //设置权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(authorities);//创建权限集合
        //将权限设置给用户
        user.setAuthorities(authorityList);
        //设置该用户拥有的菜单信息
        user.setPermissionList(permissionList);
        //返回用户信息
        return user;
    }
}
